//
//  Test.m
//  MozaFFmpeg
//
//  Created by Michael on 2020/8/21.
//

#import <UIKit/UIKit.h>
#import "MozaFFmpeg.h"
#import <mobileffmpeg/MobileFFmpegConfig.h>
#import <mobileffmpeg/MobileFFmpeg.h>

@implementation MozaFFmpeg

+ (void)idrToJpgFromSrc:(NSString *)src dst:(NSString *)dst completion:(void (^)(UIImage *image, int ret))completion {
    //NSLog(@"%@", MobileFFmpeg.getVersion);
    /*arguments[0] = "ffmpeg";
     arguments[1] = "-i";
     arguments[2] = (char *)[src UTF8String];
     arguments[3] = "-r";
     arguments[4] = "1";
     arguments[5] = "-f";
     arguments[6] = "image2";
     arguments[7] = (char *)[dst UTF8String];
     });*/
    NSArray *args = @[@"-i",
                      [NSString stringWithFormat:@"%s", src.UTF8String],
                      @"-r",
                      @"1",
                      @"-f",
                      @"image2",
                      [NSString stringWithFormat:@"%s", dst.UTF8String]];
    [self runCmdWithArgs:args completion:^(int ret) {
        !completion ?: completion([UIImage imageWithContentsOfFile:dst], ret);
    }];
}

/// 因为ffmpeg命令行里面有很多全局变量，因此同一时间内只允许一个ffmpeg命令行在运行
static dispatch_queue_t RUN_CMD_SERIAL_QUEUE = NULL;

+ (void)runCmdWithArgs:(NSArray<NSString *> *)args completion:(void (^)(int ret))completion {
    if (RUN_CMD_SERIAL_QUEUE == NULL) {
        RUN_CMD_SERIAL_QUEUE = dispatch_queue_create("com.MozaFFmpeg.runCmd.serialQueue", DISPATCH_QUEUE_SERIAL);
    }
    dispatch_async(RUN_CMD_SERIAL_QUEUE, ^{
        int rc = [MobileFFmpeg execute:[args componentsJoinedByString:@" "]];
        if (rc == RETURN_CODE_SUCCESS) {
            NSLog(@"Command execution completed successfully.\n");
        } else if (rc == RETURN_CODE_CANCEL) {
            NSLog(@"Command execution cancelled by user.\n");
        } else {
            NSLog(@"Command execution failed with rc=%d and output=%@.\n", rc, [MobileFFmpeg getLastCommandOutput]);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            !completion ?: completion(rc);
        });
    });
}

@end
